﻿
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Net
Imports System.Net.Sockets
Imports osi.root.constants
Imports osi.root.utils

Public Module _listener
    Private ReadOnly act As invoker(Of Func(Of Boolean))

    Sub New()
        act = New invoker(Of Func(Of Boolean))(GetType(TcpListener),
                                               BindingFlags.Instance Or
                                               BindingFlags.NonPublic Or
                                               BindingFlags.InvokeMethod,
                                               "get_Active")
        assert(act.valid())
        assert(act.post_binding())
    End Sub

    <Extension()> Public Function active(ByVal i As TcpListener) As Boolean
        If i Is Nothing Then
            Return False
        Else
            Return act(i)()
        End If
    End Function
End Module

Partial Public Class accepter
    Private Shared Function create_listener(ByVal add As IPAddress, ByVal port As Int32) As TcpListener
        Try
            Return New TcpListener(add, port)
        Catch ex As Exception
            raise_error(error_type.exclamation, "failed to create listener on ", add, " with port ", port)
            Return Nothing
        End Try
    End Function

    Private Shared Function start(ByVal l As TcpListener) As Boolean
        Try
            l.Start()
            Return l.active()
        Catch ex As Exception
            raise_error(error_type.exclamation,
                        "failed to start listener on ",
                        l.LocalEndpoint(),
                        ", ex ",
                        ex.Message())
            Return False
        End Try
    End Function

    Private Shared Sub [stop](ByVal l As TcpListener)
        If Not l Is Nothing Then
            l.Stop()
        End If
    End Sub
End Class
